﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BLL;
using Model;
using ServiceCenterApp.Helper;
using System.Runtime.InteropServices;

namespace ServiceCenterApp
{
    [ComVisible(true)]
    public partial class FormSearch : DevExpress.XtraEditors.XtraForm, INavigateForm
    {
        int currentPageIndex = 0;
        int pageCount = -1;
        int currentCacheIndex = 0;
        SearchView view = null;
        SearchMode mode = SearchMode.All;
        SearchBLL bll = new SearchBLL();
        CategoryBLL categoryBll = new CategoryBLL();
        KeyBLL keyBLL = new KeyBLL();
        List<KeyView> keysList = new List<KeyView>();
        List<Category> categoryList = new List<Category>();
        List<string> textList = new List<string>();
        List<Category> checkedCategoryList = new List<Category>();

        public FormSearch()
        {
            InitializeComponent();
        }

        private void loadData()
        {
            var nodes = categoryBll.GetCategoryTreeNodes();
            TreeNode root = new TreeNode("所有分类");
            root.Tag = new Category { ID = 0 };
            root.Nodes.AddRange(nodes.ToArray());
            this.Invoke(new MethodInvoker(() =>
            {
                this.treeView1.Nodes.Clear();
                this.treeView1.Nodes.Add(root);
                this.treeView1.ExpandAll();
            }));

            keysList.Clear();
            keysList.AddRange(keyBLL.GetAllKeyView());
            this.keyViewBindingSource.DataSource = null;
            this.keyViewBindingSource.DataSource = keysList;
            categoryList.Clear();
            categoryList.AddRange(categoryBll.GetAllCategory());
            this.repositoryItemCheckedComboBoxEdit1.DataSource = categoryList;
        }

        private void FormSearch_Load(object sender, EventArgs e)
        {
            this.webBrowser1.ObjectForScripting = this;
            this.webBrowser1.Navigate("about:blank");
            WinformHelper.BindRepository(repositoryItemCheckedComboBoxEdit1, categoryList, "Name", "ID");
            loadData();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.txtName.Text == "")
            {
                WinformHelper.ShowError("请输入要搜索关键词！");
                this.txtName.Select();
                return;
            }

            if (radMode.EditValue.ToString() == "产品")
            {
                mode = SearchMode.Product;
            }
            else
            {
                mode = SearchMode.Entity;
            }

            var categoryID = from xx in checkedCategoryList select xx.ID;
            var keyID = from xx in keysList where xx.Selected select xx.ID;
            view = bll.Search(this.txtName.Text, mode, categoryID.ToList(), keyID.ToList());
            BuildResultHtml();
        }

        private void BuildResultHtml()
        {
            StringBuilder sb = new StringBuilder();
            if (mode == SearchMode.Product)
            {
                PageProduct(0);
            }
            else
            {
                PageEntity(0);
            }
        }

        //显示产品详细内容
        public void ShowProductDetails(long pid)
        {
            StringBuilder sb = new StringBuilder(AppHelper.ProductDetailsTemplet);
            var p = view.ProductList.Where(x => x.ID == pid).FirstOrDefault();
            if (p == null)
            {
                this.webBrowser1.DocumentText = "找不到编号为：" + pid + "的产品！";
                return;
            }
            sb.Replace(AppHelper.P_ID_TAG, p.ID.ToString());
            sb.Replace(AppHelper.P_NAME_TAG, p.Name.ToString());
            sb.Replace(AppHelper.P_PRICE_TAG, p.Price.ToString());
            sb.Replace(AppHelper.P_SUMMARY_TAG, p.Summary.ToString());
            sb.Replace(AppHelper.P_DETAILS_TAG, p.Detail.ToString());
            sb.Replace(AppHelper.P_IDX_IMG_TAG, AppHelper.ImageRootPath + p.IndexImage);
            ShowHtml(sb.ToString());
        }

        //显示资料详细内容
        public void ShowEntityDetails(long eid)
        {
            StringBuilder sb = new StringBuilder(AppHelper.EntityDetailsTemplet);
            var p = view.EntityList.Where(x => x.ID == eid).FirstOrDefault();
            if (p == null)
            {
                this.webBrowser1.DocumentText = "找不到编号为：" + eid + "的资料！";
                return;
            }
            sb.Replace(AppHelper.E_ID_TAG, p.ID.ToString());
            sb.Replace(AppHelper.E_TITLE_TAG, p.Title.ToString());
            sb.Replace(AppHelper.E_CONTENT_TAG, p.Content.ToString());
            ShowHtml(sb.ToString());
        }

        //分页
        public void PageProduct(int index)
        {
            currentPageIndex = index;
            StringBuilder sb = new StringBuilder(AppHelper.ProductListTemplet);
            sb.Replace(AppHelper.P_COUNT_TAG, view.ProductList.Count + "");
            sb.Replace(AppHelper.USED_TIME_TAG, 4 + "");

            StringBuilder sb0 = new StringBuilder();
            for (int i = currentPageIndex * AppHelper.PageSize; i < (currentPageIndex + 1) * AppHelper.PageSize && i < view.ProductList.Count; i++)
            {
                sb0.Append("<div class='ProductPanel' onclick='ShowDetails(" + view.ProductList[i].ID + ")'>").Append("<div class='Name'>").Append(view.ProductList[i].Name).Append("</div>")
                    .Append("<div>").Append("<img src='" + AppHelper.ImageRootPath + view.ProductList[i].IndexImage + "'></img></div>").Append("<div class='Price'>价格：<b>").Append(view.ProductList[i].Price)
                    .Append("</b></div>").Append("</div>");
            }
            sb0.Append("<div class='clear'></div>");
            sb.Replace(AppHelper.P_PANEL_TAG, sb0.ToString());
            sb.Replace(AppHelper.P_PAGE_TAG, GetPageHtml(view.ProductList.Count));
            ShowHtml(sb.ToString());
        }

        private void PageEntity(int index)
        {
            currentPageIndex = index;
            StringBuilder sb = new StringBuilder(AppHelper.EntityListTemplet);
            sb.Replace(AppHelper.E_COUNT_TAG, view.EntityList.Count + "");
            sb.Replace(AppHelper.USED_TIME_TAG, 4 + "");

            StringBuilder sb0 = new StringBuilder();
            for (int i = currentPageIndex * AppHelper.PageSize; i < (currentPageIndex + 1) * AppHelper.PageSize && i < view.EntityList.Count; i++)
            {
                sb0.Append("<div class='EntityPanel' onclick='ShowDetails(" + view.EntityList[i].ID + ")'>").
                    Append("<div class='ID'>编号：<span>").Append(view.EntityList[i].ID).Append("</span></div>").
                    Append("<div class='Title'>").Append(view.EntityList[i].Title).Append("</div><div class='clear'></div></div>");
            }
            sb0.Append("<div class='clear'></div>");
            sb.Replace(AppHelper.E_PANEL_TAG, sb0.ToString());
            sb.Replace(AppHelper.E_PAGE_TAG, GetPageHtml(view.EntityList.Count));
            ShowHtml(sb.ToString());
        }

        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnNew_Click(null, null);
            }
        }

        private string GetPageHtml(int count)
        {
            if (count < AppHelper.PageSize)
            {
                return "";
            }
            StringBuilder sb0 = new StringBuilder();
            if (pageCount < 0)
            {
                pageCount = count / AppHelper.PageSize;
                if (count % AppHelper.PageSize != 0)
                {
                    pageCount++;
                }
            }

            sb0.Append("<div class=\"xm-pagenavi\">");
            if (currentPageIndex == 0)
            {
                sb0.Append("<span class=\"numbers current\">1</span>");
            }
            else
            {
                sb0.Append("<a class=\"numbers\" href=\"javascript:Page(0);\">1</a>");
            }
            int start = currentPageIndex - 3;
            if (start <= 0)
            {
                start = 1;
            }
            else
            {
                sb0.Append("<span class=\"numbers\">…</span>");
            }
            int end = currentPageIndex + 3;
            if (end > pageCount - 1)
            {
                end = pageCount - 1;
            }
            else if (end < pageCount - 1)
            {
                sb0.Append("<span class=\"numbers\">…</span>");
            }

            for (int i = start; i <= end; i++)
            {
                if (i == currentPageIndex)
                {
                    sb0.Append("<span class=\"numbers current\">" + (i + 1) + "</span>");
                }
                else
                {
                    sb0.Append("<a class=\"numbers\" href=\"javascript:Page(" + i + ");\">" + (i + 1) + "</a>");
                }
            }
            sb0.Append("</div>");

            return sb0.ToString();
        }

        private void ShowHtml(string text)
        {
            this.webBrowser1.DocumentText = text;
            textList.Add(text);
            currentCacheIndex++;
            if (textList.Count > 16)
            {
                currentCacheIndex = 15;
                textList.RemoveAt(0);
            }
        }

        public void Back()
        {
            currentCacheIndex--;
            if (currentCacheIndex < 0)
            {
                currentCacheIndex = 0;
                Program.MainWindow.ShowMessage("已经到了起始点，不能在后退了！");
            }
            if (currentCacheIndex < textList.Count && currentCacheIndex > -1)
            {
                this.webBrowser1.DocumentText = textList[currentCacheIndex];
            }
        }

        public void Forward()
        {
            currentCacheIndex++;
            if (currentCacheIndex >= textList.Count)
            {
                currentCacheIndex = textList.Count - 1;
                Program.MainWindow.ShowMessage("已经到了结束点，不能在前进了！");
            }
            if (currentCacheIndex < textList.Count && currentCacheIndex > -1)
            {
                this.webBrowser1.DocumentText = textList[currentCacheIndex];
            }
        }

        private void sbCopy_Click(object sender, EventArgs e)
        {
            this.webBrowser1.Document.ExecCommand("selectAll", false, null);
            this.webBrowser1.Document.ExecCommand("Copy", false, null);
        }

        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            var category = e.Node.Tag as Category;
            if (category == null) { return; }
            if (e.Node.Checked)
            {
                checkedCategoryList.Add(category);
            }
            else
            {
                checkedCategoryList.Remove(category);
            }
        }
    }
}